package com.meilai.project.service.other.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.thirdPart.TencentDistrictDTO;
import com.meilai.project.entity.other.PCA;
import com.meilai.project.mapper.other.PCAMapper;
import com.meilai.project.service.other.PCAService;
import com.meilai.project.vo.SelectOptionVO;
import com.meilai.project.vo.other.PCAVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张驰
 * @date 2021/3/15 14:26
 */
@Service
public class PCAServiceImpl extends ServiceImpl<PCAMapper, PCA> implements PCAService {

    @Override
    public void insertByTencentMap(JSONObject data) {
        List<PCA> pcas = new ArrayList<>();

        JSONArray result = data.getJSONArray("result");
        List<TencentDistrictDTO> ps = JSON.parseArray(JSON.toJSONString(result.get(0)), TencentDistrictDTO.class);
        List<TencentDistrictDTO> cs = JSON.parseArray(JSON.toJSONString(result.get(1)), TencentDistrictDTO.class);
        List<TencentDistrictDTO> as = JSON.parseArray(JSON.toJSONString(result.get(2)), TencentDistrictDTO.class);

        for(TencentDistrictDTO _p : ps){
            pcas.add(packDoorPCA(_p,0L));

            if(CollectionUtils.isEmpty(_p.getCidx())) continue;
            for(int i=_p.getCidx().get(0);i<=_p.getCidx().get(1);i++){
                TencentDistrictDTO _c = cs.get(i);
                pcas.add(packDoorPCA(_c,_p.getId()));

                if(CollectionUtils.isEmpty(_c.getCidx())) continue;
                for(int j=_c.getCidx().get(0);j<=_c.getCidx().get(1);j++){
                    TencentDistrictDTO _a = as.get(j);
                    pcas.add(packDoorPCA(_a,_c.getId()));
                }
            }
        }

        saveBatch(pcas);
    }

    private PCA packDoorPCA(TencentDistrictDTO _pca, Long pid){
        PCA pca = new PCA();
        BeanUtils.copyProperties(_pca, pca);
        pca.setPid(pid);
        pca.setLat(_pca.getLocation().getLat());
        pca.setLng(_pca.getLocation().getLng());
        if(CollectionUtils.isNotEmpty(_pca.getPinyin())) pca.setPinyin(StringUtils.join(_pca.getPinyin().toArray(), ","));
        return pca;
    }

    @Override
    public List<SelectOptionVO> pcaList(Long pid) {
        return baseMapper.pcaList(pid);
    }

    @Override
    public List<PCAVO> pcAll() {
        return baseMapper.pcAll();
    }

    @Override
    public List<PCAVO> pcaByPid(Long pid) {
        return baseMapper.pacByPid(pid);
    }

    @Override
    public PCA getOnePCAById(Long id) {
        return getById(id);
    }
}
